import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Card, message, Button, Table, Modal, Image } from 'antd';
import PropTypes from 'prop-types';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import styles from '@/components/common/PateoTable/TableList.less';
import { filterAuth } from '@/support/common';
import { DownOutlined, RightOutlined } from '@ant-design/icons';
import HandleModel from './handleModel';
import ActiveModel from './activeModel';
import DeleteAssociationModal from './deleteAssociationModal';
import MaskText from '@/components/MaskText';

const mapStateToProps = (state: any) => ({
  DriverMng: state.DriverMng,
  loading: state.loading.models['DriverMng'],
  permissions: state?.menu?.permissions,
  user: state?.menu?.userProfile,
});
class DriverMng extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      modalVisible: false,
      formData: {},
      exportVisible: false,
      previewVisible: false,
      previewImage: '',
      fireVisible: false,
      activeVisible: false,
      activeInfo: {},
      isActive: true,
      deleteAssociationVisible: false,
      delModalVisible: false,
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'DriverMng/getFetchPage',
      payload: {
        url: '/msalcohollock/driver/page',
        ...formValues,
      },
    });
  }
  handleFormReset = (fields: any) => {
    this.setState({
      formValues: {},
    });
  };
  //  新增
  handleAdd = () => {
    this.setState({
      modalVisible: true,
      formData: {},
    });
  };

  //  编辑
  handleEdit = (data: any) => {
    // const { sid, vin, happenDate, address, status, remark, } = data
    this.setState({
      modalVisible: true,
      formData: {
        ...data,
      },
    });
  };
  closeModal = () => {
    this.setState({
      modalVisible: false,
      formData: {},
    });
  };
  // //批量导入
  // handleExport = () => {
  //   this.setState({
  //       exportVisible: true,
  //   });
  // };
  // closeExportModal = () =>{
  //   this.setState({
  //       exportVisible: false,
  //     });
  // }
  handleFreshPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'DriverMng/getFetchPage',
      payload: {
        url: '/msalcohollock/driver/page',
        ...formValues,
      },
    });
  };

  //  删除
  handleDelete = () => {
    const { dispatch } = this.props;
    const { formData } = this.state;
    this.setState({ loading: true });
    dispatch({
      type: 'DriverMng/delData',
      payload: { url: `/msalcohollock/driver/${formData.sid}` },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('删除成功');
          this.cloleDelModal();
          this.handleFreshPage();
        }
      },
    }).finally(() => this.setState({ loading: false }));
  };
  //查看照片
  showPhoto = (record: any) => {
    this.setState({
      previewImage: record.facePictureUrl,
      previewVisible: true,
    });
  };
  handleCancel = () => this.setState({ previewVisible: false });
  //远程启动
  remoteFire = (record: any) => {
    this.setState({
      fireVisible: true,
    });
  };
  handleCancelFire = () => this.setState({ fireVisible: false });
  handleFire = () => {
    const { dispatch } = this.props;
    const { activeInfo } = this.state;
    const postData = { sid: activeInfo.sid, vin: activeInfo.vin };
    this.setState({
      loading: true,
    });
    dispatch({
      type: 'DriverMng/postObj',
      payload: {
        url: '/msalcohollock/driver/remote/start/vehicle',
        ...postData,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('远程启动成功');
          this.handleFreshPage();
          this.handleCancelFire();
        } else {
          message.warning(`远程启动成功失败,${res.statusMessage}`);
        }
      },
    }).finally(() =>
      this.setState({
        loading: false,
      }),
    );
  };
  //激活监控
  handleActive = (record: any) => {
    this.setState({
      activeVisible: true,
      activeInfo: record,
      isActive: true,
    });
  };
  closeActiveModal = () => {
    this.setState({
      activeVisible: false,
      activeInfo: {},
      isActive: true,
    });
  };
  cancelActive = (record: any) => {
    this.setState({
      activeVisible: true,
      activeInfo: record,
      isActive: false,
    });
  };
  handleDeleteAssociation = (record: any) => {
    this.setState({
      deleteAssociationVisible: true,
      activeInfo: record,
    });
  };
  closeDeleteModal = () => {
    this.setState({
      deleteAssociationVisible: false,
      activeInfo: {},
    });
  };

  cloleDelModal = () => {
    this.setState({ delModalVisible: false });
  };
  render() {
    const {
      DriverMng: {
        pageData: { pagination, list },
      },
      loading,
      permissions,
      location: { pathname = '/' },
    } = this.props;
    list.forEach((t: any) => {
      !t.vehicleList && (t.vehicleList = []);
    });
    const {
      formValues,
      modalVisible,
      formData,
      previewVisible,
      previewImage,
      activeVisible,
      activeInfo,
      isActive,
      deleteAssociationVisible,
      loading: ModalButtonLoading,
      delModalVisible,
    } = this.state;
    // const burningStatus = getDictOptionsByCode(this.context.dicData, 'burningStatus')
    // const list = [
    //   {
    //     sid: 1,
    //     phoneNumber: '13111111111',
    //     name: '小王',
    //     fleetName: 'xxx车辆运营有限公司',
    //     facePictureUrl: 'https://xxx',
    //     vehicleCount: 2,
    //     monitorCount: 1,
    //     vehicleList: [
    //       {
    //         vin: 'VIN001',
    //         licencePlate: '鄂AXXXXX',
    //         cboxCode: 'b001',
    //         monitorState: 0,
    //       },
    //       {
    //         vin: 'vin002',
    //         licencePlate: '鄂AXXXXX',
    //         cboxCode: 'b002',
    //         monitorState: 1,
    //       },
    //     ],
    //   },
    //   {
    //     sid: 2,
    //     phoneNumber: '1322222222',
    //     name: '小黄',
    //     fleetName: 'xxx车辆运营有限公司',
    //     facePictureUrl: 'https://xxx',
    //     vehicleCount: 2,
    //     monitorCount: 1,
    //     vehicleList: [
    //       {
    //         vin: 'VIN001',
    //         licencePlate: '鄂AXXXXX',
    //         cboxCode: 'b001',
    //         monitorState: 0,
    //       },
    //       {
    //         vin: 'vin002',
    //         licencePlate: '鄂AXXXXX',
    //         cboxCode: 'b002',
    //         monitorState: 1,
    //       },
    //     ],
    //   },
    // ];
    // {sid:2,phoneNumber:'22222',name:'司机一二',fleetName:'哈喽微微车队',facePictureUrl:'https://int-cms-1305685802.cos.ap-shanghai.myqcloud.com/img/proxy_qr_img/f0a067d8ea4c4c2f.PNG',vehicleCount: 3,monitorCount:1, vehicleList:[{vin:'1111111',handheldsCode:'手持机编号1', cboxCode:'控制盒编号1',monitorState:0},{vin:'777777',handheldsCode:'手持机编号2', cboxCode:'控制盒编号2',monitorState:1}]}]
    const page = {
      current: pagination.pageNo || 1,
      pageSize: pagination.pageSize,
      total: pagination.totalSize,
    };

    const searchItems = [
      {
        title: '司机ID',
        type: 'input',
        key: 'sid',
        maxLength: 50,
        rules: [
          {
            required: false,
            // message: '请输入英文及数字!',
            // pattern: '^[a-zA-Z0-9]*$',
            message: '请输入数字',
            pattern: /^\d+$/,
          },
        ],
      },
      {
        title: '司机姓名',
        type: 'input',
        key: 'name',
        maxLength: 50,
        rules: [
          {
            required: false,
            // message: '请输入英文及数字!',
            // pattern: '^[a-zA-Z0-9]*$',
            message: '不能输入空字符!',
            pattern: /^\S+$/,
          },
        ],
      },
      {
        title: '司机手机号',
        type: 'input',
        key: 'phoneNumber',
        maxLength: 50,
        rules: [
          {
            required: false,
            // message: '请输入英文及数字!',
            // pattern: '^[a-zA-Z0-9]*$',
            message: '手机号为数字',
            pattern: /^\d+$/,
          },
        ],
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...page,
      showTotal: () => <span>共&nbsp;{page?.total}&nbsp;条</span>,
    };

    const columns = [
      {
        title: '司机ID',
        dataIndex: 'sid',
      },
      {
        title: '司机手机号',
        dataIndex: 'phoneNumber',
        render(val: any) {
          return <MaskText text={val} type="phone" />;
        },
      },
      {
        title: '姓名',
        dataIndex: 'name',
      },
      {
        title: '所属车队',
        dataIndex: 'fleetName',
      },
      {
        title: '人脸照片',
        dataIndex: 'facePictureUrl',
        render: (text: any, record: any) => {
          return text ? (
            <a
              onClick={() => {
                this.showPhoto(record);
              }}
            >
              <div>查看</div>
            </a>
          ) : (
            ''
          );
        },
      },
      {
        title: '司机关联车辆数量',
        dataIndex: 'vehicleCount',
      },
      {
        title: '激活监控车辆数',
        dataIndex: 'monitorCount',
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 150,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'driverMng_doEdit',
              onConfirm: () => {
                this.handleEdit(record);
              },
            },
            {
              title: '删除',
              key: 'del',
              auth: 'driverMng_doDel',
              onConfirm: () => {
                this.setState({ delModalVisible: true });
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={4} pathname={pathname} />;
        },
      },
    ];
    const subColumns = [
      {
        title: '司机关联车辆VIN',
        dataIndex: 'vin',
      },
      {
        title: '手持机编号',
        dataIndex: 'handheldsCode',
      },
      {
        title: '控制盒编号',
        dataIndex: 'cboxCode',
      },
      {
        title: '监控激活状态',
        dataIndex: 'monitorState',
        render: (text: any, record: any) => {
          if (text == 0) {
            return '未激活';
          } else if (text == 1) {
            return '已激活';
          } else {
            return text;
          }
        },
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 150,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '激活监控',
              key: 'active',
              auth: 'driverMng_doEdit',
              hide: record.monitorState == 1,
              onConfirm: () => {
                this.handleActive(record);
              },
            },
            {
              title: '撤销激活',
              key: 'invalid',
              auth: 'driverMng_doEdit',
              hide: record.monitorState == 0,
              onConfirm: () => {
                this.cancelActive(record);
              },
            },
            {
              title: '远程启动',
              key: 'fire',
              auth: 'driverMng_doEdit',
              hide: record.monitorState == 0,
              onConfirm: () => {
                this.remoteFire(record);
              },
            },
            {
              title: '删除关联',
              key: 'del',
              auth: 'driverMng_doDel',
              onConfirm: () => {
                this.handleDeleteAssociation(record);
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={4} pathname={pathname} />;
        },
      },
    ];
    const tableProps = {
      key: 'sid',
      columns,
      dataSource: list,
      loading,
      bordered: true,
      expandable: {
        expandedRowRender: (record: any) => {
          return (
            <Table
              columns={subColumns}
              rowKey={(record: any) => record.vin}
              dataSource={
                record.vehicleList?.map((item: any) => {
                  return {
                    ...item,
                    sid: record.sid,
                    phoneNumber: record.phoneNumber,
                    name: record.name,
                    lisencePlate: record.lisencePlate || '',
                    facePictureUrl: record.facePictureUrl || '',
                  };
                }) ?? undefined
              }
              onRow={record => ({
                onClick: () => {
                  this.setState({ activeInfo: record });
                },
              })}
              pagination={false}
            />
          );
        },
        expandIcon: ({ expanded, onExpand, record }) => {
          if (!record.vehicleList.length && !expanded) return null;
          return expanded ? (
            <DownOutlined onClick={e => onExpand(record, e)} />
          ) : (
            <RightOutlined onClick={e => onExpand(record, e)} />
          );
        },
      },
      rowKey: (record: any) => record.sid,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
      onRow: (record: any) => ({ onClick: () => this.setState({ formData: record }) }),
    };
    const footer = (
      <div>
        <Button size="small" onClick={this.handleCancelFire}>
          取消
        </Button>
        <Button size="small" loading={ModalButtonLoading} onClick={this.handleFire} type="primary">
          确定
        </Button>
      </div>
    );
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'DriverMng/getFetchPage',
              url: '/msalcohollock/driver/page',
              extraArgs: {},
            }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
          />
        </Card>
        <Card className={styles.standardTable}>
          <div className="my_newItem">
            {filterAuth('driverMng_doAdd', permissions, pathname) ? (
              <Button size="small" type="primary" onClick={this.handleAdd}>
                新增司机
              </Button>
            ) : null}
            {/* {filterAuth('handsetMng_doExport', permissions, pathname) ? (
            <Button size="small" type="primary" onClick={this.handleExport}>
              批量导入
            </Button>
        ) : null} */}
          </div>
          <PateoTable
            extraHandle={true}
            currentName={'page'}
            pageSizeName={'size'}
            tableProps={tableProps}
            fetchParams={{ type: 'DriverMng/getFetchPage', url: '/msalcohollock/driver/page' }}
            formValues={formValues}
          />
        </Card>
        <HandleModel
          modalVisible={modalVisible}
          formData={formData}
          closeModal={this.closeModal}
          freshPage={this.handleFreshPage}
        ></HandleModel>
        {/* <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="" style={{ width: '100%' }} src={previewImage} />
        </Modal> */}
        <Image
          width={200}
          // height={'80vh'}
          style={{ display: 'none' }}
          // src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png?x-oss-process=image/blur,r_50,s_50/quality,q_1/resize,m_mfit,h_200,w_200"
          preview={{
            visible: previewVisible,
            src: previewImage,
            onVisibleChange: value => {
              this.handleCancel();
            },
          }}
        />
        <Modal
          title={'远程启动'}
          visible={this.state.fireVisible}
          footer={footer}
          onCancel={this.handleCancelFire}
        >
          <p>
            远程启动后，<b style={{ color: 'red' }}>所有人</b>将可正常启动该车辆（仅一次），
            <b style={{ color: 'red' }}>不进行司机身份校验、酒精测试</b>，确定要远程启动吗？
          </p>
        </Modal>
        <ActiveModel
          modalVisible={activeVisible}
          formData={activeInfo}
          closeModal={this.closeActiveModal}
          freshPage={this.handleFreshPage}
          isActive={isActive}
        ></ActiveModel>
        <DeleteAssociationModal
          modalVisible={deleteAssociationVisible}
          formData={activeInfo}
          closeModal={this.closeDeleteModal}
          freshPage={this.handleFreshPage}
        ></DeleteAssociationModal>
        {/* <ExportModal
         modalVisible={exportVisible}
         closeModal={this.closeExportModal}
         freshPage={this.handleFreshPage}
         >
        </ExportModal> */}
        <Modal
          title={'删除司机'}
          okButtonProps={{ size: 'small' }}
          cancelButtonProps={{ size: 'small' }}
          centered
          visible={delModalVisible}
          confirmLoading={ModalButtonLoading}
          onOk={this.handleDelete}
          onCancel={this.cloleDelModal}
        >
          <div style={{ textAlign: 'center' }}>{`确定要删除司机"${formData.name}"吗?`}</div>
        </Modal>
      </div>
    );
  }
}
export default connect(mapStateToProps)(DriverMng);
